import { ApiService } from "./index";
import type {
  AppInfo,
  SystemStatus,
  Notification,
  HealthCheck,
  SystemStats,
  FeatureLimits,
  AnnouncementData,
} from "@/types/app";

class AppApiService extends ApiService {
  // 应用信息
  async getAppInfo() {
    return this.get<AppInfo>("/app/info");
  }

  async updateAppConfig(config: Partial<AppInfo>) {
    return this.put<AppInfo>("/app/config", config);
  }

  // 系统状态
  async getSystemStatus() {
    return this.get<SystemStatus>("/app/status");
  }

  async getHealthCheck() {
    return this.get<HealthCheck>("/app/health");
  }

  async getSystemStats() {
    return this.get<SystemStats>("/app/stats");
  }

  async getSystemMetrics(params?: {
    timeRange?: "1h" | "24h" | "7d" | "30d";
    metrics?: string[];
  }) {
    const queryParams = new URLSearchParams();
    if (params?.timeRange) queryParams.append("timeRange", params.timeRange);
    if (params?.metrics) {
      params.metrics.forEach((metric) => queryParams.append("metrics", metric));
    }

    const url = `/app/metrics${queryParams.toString() ? "?" + queryParams.toString() : ""}`;
    return this.get<{
      cpu: Array<{ timestamp: string; value: number }>;
      memory: Array<{ timestamp: string; value: number }>;
      disk: Array<{ timestamp: string; value: number }>;
      network: Array<{ timestamp: string; in: number; out: number }>;
      requests: Array<{
        timestamp: string;
        count: number;
        avgResponseTime: number;
      }>;
      errors: Array<{ timestamp: string; count: number }>;
    }>(url);
  }

  // 通知管理
  async getNotifications(params?: {
    page?: number;
    limit?: number;
    type?: "info" | "success" | "warning" | "error";
    read?: boolean;
  }) {
    const queryParams = new URLSearchParams();
    if (params?.page) queryParams.append("page", params.page.toString());
    if (params?.limit) queryParams.append("limit", params.limit.toString());
    if (params?.type) queryParams.append("type", params.type);
    if (params?.read !== undefined)
      queryParams.append("read", params.read.toString());

    const url = `/app/notifications${queryParams.toString() ? "?" + queryParams.toString() : ""}`;
    return this.get<{
      notifications: Notification[];
      total: number;
      unreadCount: number;
    }>(url);
  }

  async markNotificationAsRead(notificationId: string) {
    return this.post(`/app/notifications/${notificationId}/read`);
  }

  async markAllNotificationsAsRead() {
    return this.post("/app/notifications/read-all");
  }

  async deleteNotification(notificationId: string) {
    return this.delete(`/app/notifications/${notificationId}`);
  }

  async clearAllNotifications() {
    return this.delete("/app/notifications/clear-all");
  }

  async createNotification(data: {
    title: string;
    message: string;
    type: "info" | "success" | "warning" | "error";
    targetUsers?: string[];
    expiresAt?: string;
    actionUrl?: string;
    actionText?: string;
  }) {
    return this.post<Notification>("/app/notifications", data);
  }

  // 公告管理
  async getAnnouncements(params?: {
    active?: boolean;
    type?: "maintenance" | "feature" | "update" | "general";
  }) {
    const queryParams = new URLSearchParams();
    if (params?.active !== undefined)
      queryParams.append("active", params.active.toString());
    if (params?.type) queryParams.append("type", params.type);

    const url = `/app/announcements${queryParams.toString() ? "?" + queryParams.toString() : ""}`;
    return this.get<AnnouncementData[]>(url);
  }

  async getAnnouncement(announcementId: string) {
    return this.get<AnnouncementData>(`/app/announcements/${announcementId}`);
  }

  async dismissAnnouncement(announcementId: string) {
    return this.post(`/app/announcements/${announcementId}/dismiss`);
  }

  // 功能限制
  async getFeatureLimits() {
    return this.get<FeatureLimits>("/app/limits");
  }

  async checkFeatureAvailability(feature: string) {
    return this.get<{
      available: boolean;
      reason?: string;
      upgradeRequired?: boolean;
    }>(`/app/features/${feature}/availability`);
  }

  async getFeatureUsage(feature: string) {
    return this.get<{
      used: number;
      limit: number;
      resetAt?: string;
      percentage: number;
    }>(`/app/features/${feature}/usage`);
  }

  // 系统设置
  async getSystemSettings() {
    return this.get<Record<string, any>>("/app/settings");
  }

  async updateSystemSettings(settings: Record<string, any>) {
    return this.put("/app/settings", settings);
  }

  async getSystemSetting(key: string) {
    return this.get<{ value: any }>(`/app/settings/${key}`);
  }

  async updateSystemSetting(key: string, value: any) {
    return this.put(`/app/settings/${key}`, { value });
  }

  // 维护模式
  async enableMaintenanceMode(data: {
    message?: string;
    estimatedDuration?: number;
    allowedUsers?: string[];
  }) {
    return this.post("/app/maintenance/enable", data);
  }

  async disableMaintenanceMode() {
    return this.post("/app/maintenance/disable");
  }

  async getMaintenanceStatus() {
    return this.get<{
      enabled: boolean;
      message?: string;
      startedAt?: string;
      estimatedEndAt?: string;
      allowedUsers?: string[];
    }>("/app/maintenance/status");
  }

  // 错误报告
  async reportError(error: {
    message: string;
    stack?: string;
    url?: string;
    userAgent?: string;
    userId?: string;
    sessionId?: string;
    metadata?: Record<string, any>;
  }) {
    return this.post("/app/errors/report", error);
  }

  async getErrorReports(params?: {
    page?: number;
    limit?: number;
    severity?: "low" | "medium" | "high" | "critical";
    resolved?: boolean;
    dateFrom?: string;
    dateTo?: string;
  }) {
    const queryParams = new URLSearchParams();
    if (params?.page) queryParams.append("page", params.page.toString());
    if (params?.limit) queryParams.append("limit", params.limit.toString());
    if (params?.severity) queryParams.append("severity", params.severity);
    if (params?.resolved !== undefined)
      queryParams.append("resolved", params.resolved.toString());
    if (params?.dateFrom) queryParams.append("dateFrom", params.dateFrom);
    if (params?.dateTo) queryParams.append("dateTo", params.dateTo);

    const url = `/app/errors${queryParams.toString() ? "?" + queryParams.toString() : ""}`;
    return this.get<{
      errors: Array<{
        id: string;
        message: string;
        stack?: string;
        count: number;
        firstSeen: string;
        lastSeen: string;
        severity: string;
        resolved: boolean;
      }>;
      total: number;
      page: number;
      totalPages: number;
    }>(url);
  }

  // 日志管理
  async getLogs(params?: {
    level?: "debug" | "info" | "warn" | "error";
    service?: string;
    limit?: number;
    since?: string;
  }) {
    const queryParams = new URLSearchParams();
    if (params?.level) queryParams.append("level", params.level);
    if (params?.service) queryParams.append("service", params.service);
    if (params?.limit) queryParams.append("limit", params.limit.toString());
    if (params?.since) queryParams.append("since", params.since);

    const url = `/app/logs${queryParams.toString() ? "?" + queryParams.toString() : ""}`;
    return this.get<
      Array<{
        timestamp: string;
        level: string;
        service: string;
        message: string;
        metadata?: Record<string, any>;
      }>
    >(url);
  }

  async downloadLogs(params?: {
    dateFrom?: string;
    dateTo?: string;
    level?: string;
    service?: string;
  }) {
    const queryParams = new URLSearchParams();
    if (params?.dateFrom) queryParams.append("dateFrom", params.dateFrom);
    if (params?.dateTo) queryParams.append("dateTo", params.dateTo);
    if (params?.level) queryParams.append("level", params.level);
    if (params?.service) queryParams.append("service", params.service);

    const url = `/app/logs/download${queryParams.toString() ? "?" + queryParams.toString() : ""}`;
    return this.download(url, "system-logs.txt");
  }

  // 缓存管理
  async clearCache(cacheType?: "all" | "user" | "session" | "api" | "static") {
    const data = cacheType ? { type: cacheType } : {};
    return this.post("/app/cache/clear", data);
  }

  async getCacheStats() {
    return this.get<{
      totalSize: number;
      hitRate: number;
      missRate: number;
      evictionCount: number;
      cacheTypes: Record<
        string,
        {
          size: number;
          entries: number;
          hitRate: number;
        }
      >;
    }>("/app/cache/stats");
  }

  // 数据库管理
  async getDatabaseStats() {
    return this.get<{
      connections: {
        active: number;
        idle: number;
        total: number;
      };
      queries: {
        total: number;
        slow: number;
        avgExecutionTime: number;
      };
      storage: {
        used: number;
        available: number;
        total: number;
      };
    }>("/app/database/stats");
  }

  async optimizeDatabase() {
    return this.post("/app/database/optimize");
  }

  // 备份管理
  async createBackup(data?: {
    type?: "full" | "incremental";
    description?: string;
  }) {
    return this.post("/app/backup/create", data);
  }

  async getBackups() {
    return this.get<
      Array<{
        id: string;
        type: string;
        size: number;
        createdAt: string;
        description?: string;
        status: "pending" | "completed" | "failed";
      }>
    >("/app/backup/list");
  }

  async restoreBackup(backupId: string) {
    return this.post(`/app/backup/${backupId}/restore`);
  }

  async deleteBackup(backupId: string) {
    return this.delete(`/app/backup/${backupId}`);
  }

  async downloadBackup(backupId: string) {
    return this.download(`/app/backup/${backupId}/download`);
  }

  // 任务管理
  async getTasks(params?: {
    status?: "pending" | "running" | "completed" | "failed";
    type?: string;
    limit?: number;
  }) {
    const queryParams = new URLSearchParams();
    if (params?.status) queryParams.append("status", params.status);
    if (params?.type) queryParams.append("type", params.type);
    if (params?.limit) queryParams.append("limit", params.limit.toString());

    const url = `/app/tasks${queryParams.toString() ? "?" + queryParams.toString() : ""}`;
    return this.get<
      Array<{
        id: string;
        type: string;
        status: string;
        progress: number;
        createdAt: string;
        startedAt?: string;
        completedAt?: string;
        error?: string;
        result?: any;
      }>
    >(url);
  }

  async getTask(taskId: string) {
    return this.get<{
      id: string;
      type: string;
      status: string;
      progress: number;
      createdAt: string;
      startedAt?: string;
      completedAt?: string;
      error?: string;
      result?: any;
      logs: Array<{
        timestamp: string;
        level: string;
        message: string;
      }>;
    }>(`/app/tasks/${taskId}`);
  }

  async cancelTask(taskId: string) {
    return this.post(`/app/tasks/${taskId}/cancel`);
  }

  async retryTask(taskId: string) {
    return this.post(`/app/tasks/${taskId}/retry`);
  }

  // 版本管理
  async getVersionInfo() {
    return this.get<{
      current: string;
      latest: string;
      updateAvailable: boolean;
      changelog?: string;
      releaseNotes?: string;
    }>("/app/version");
  }

  async checkForUpdates() {
    return this.post<{
      updateAvailable: boolean;
      version?: string;
      changelog?: string;
      critical?: boolean;
    }>("/app/version/check");
  }

  // 许可证管理
  async getLicenseInfo() {
    return this.get<{
      type: "free" | "pro" | "enterprise";
      expiresAt?: string;
      features: string[];
      limits: Record<string, number>;
      valid: boolean;
    }>("/app/license");
  }

  async validateLicense(licenseKey: string) {
    return this.post<{
      valid: boolean;
      type?: string;
      expiresAt?: string;
      features?: string[];
    }>("/app/license/validate", { licenseKey });
  }

  async activateLicense(licenseKey: string) {
    return this.post("/app/license/activate", { licenseKey });
  }
}

export const appApi = new AppApiService();
export default appApi;
